/*
 * Ex:			
 * File name:   test.cpp
 *
 *  Created on: Apr 6, 2012
 *      Author: ayash
 *
 *
 * Descriptor:
 *
 */

#include <iostream>

#include "uthreads.h"
#include "user_thread.h"
#include "common_defs.h"

#define SECOND 1000000

using namespace std;

void first_thread_func(void)
{
	int res;

	cout << "\nfirst thread woke up!!!\n" << endl;

	usleep(2*SECOND);

	res = thread_set_priority( 1 , MAX_PRI );
	if ( -1 == res )
	{
		cerr <<  __LINE__ << ": thread_set_priority() failed\n" << endl;
	}

}



int main()
{
	UserThread *first;
	UserThread *second;
	result_t result = OPERATION_SUCCESS;
	int res;

	//	----------------------------->
	//		user thread tests
	//	----------------------------->

	first = new UserThread(1, 2 );
	second = new UserThread(2, 3 );

	cout << "Testing user_thread class:\n" << endl;
	// compare 2 threads with different priority
	if ( ! ThreadsComparator().operator ()(first,second) )
	{
		cerr << "wrong comparison between threads pointers !\n";
		result = ERROR_INVALID_ARGUMENTS;
	}

	if ( ThreadsComparator().operator ()(second,first) )
	{
		cerr << "wrong comparison between threads pointers !\n";
		result = ERROR_INVALID_ARGUMENTS;
	}

	delete first;
	delete second;

	second = new UserThread(1, 2 );
	first = new UserThread(2, 2 );
	second->set_thread_state(THREAD_STATE_READY);
	first->set_thread_state(THREAD_STATE_READY);
	// compare 2 threads with different priority
	if ( ! ThreadsComparator().operator ()(second,first) )
	{
		cerr << "wrong comparison between threads pointers !\n";
		result = ERROR_INVALID_ARGUMENTS;
	}
	delete first;
	delete second;

	if ( OPERATION_SUCCESS != result )
	{
		cerr << "user_thread class test failed\n" << endl;
	}
	else
	{
		cout << "user_thread class test passed!!!\n" << endl;
	}


	res = thread_lib_init();
	if ( res )
	{
		cerr << "thread_lib_init failed\n" << endl;
		return res;
	}

	res = thread_spawn( first_thread_func ,  0 );
	if ( -1 == res )
	{
		cerr <<  __LINE__ << ": thread_spawn() failed\n" << endl;
	}


	res = thread_terminate(0);
	if ( res )
	{
		cerr << "thread_terminate with main thread failed!!\n" << endl;
		return res;
	}

	return result;


}


